package com.dict.controller;

import com.alibaba.excel.EasyExcel;
import com.dict.pojo.Dict;
import com.dict.pojo.ExcelDTO;
import com.dict.service.DictService;
import com.srb.common.BusinessException;
import com.srb.common.R;
import com.srb.common.ResponseEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author 宋伟宁
 * @Date 2024/3/6
 * @Version 1.0
 **/
@RestController
@Schema(description = "字典管理")
@RequestMapping("/dict")
//@CrossOrigin
public class AdminDictController {

    @Resource
    private DictService dictService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;




    @PostMapping("/")
    public R save(@RequestParam(name = "pid",required = false) Long parentId,String name) {
        this.dictService.addDict(parentId,name);
        return R.ok().message("添加成功");
    }
    @GetMapping("/{name}")
    public R getDictByName(@PathVariable("name") String name) {
        //读取Redis获取数据
        Boolean flag= this.dictService.checkDictByName(name);
        return flag ? R.ok().message("已经存在") :
                R.ok().message("可以使用");
    }


    @GetMapping("/parent")
    @Operation(description = "查询所有父字典", tags = "字典管理", method = "GET")
    public R getParentDict() {
        //读取Redis获取数据
        List<Dict> dicts =(List<Dict>) this.redisTemplate.opsForValue().get("parentDict");
        if(null == dicts  || dicts.size() == 0){
            dicts=this.dictService.listByParentId(null);
            this.redisTemplate.opsForValue().set("parentDict",dicts);
        }
        //如果存在：获取即可
        return R.ok().data("dicts", dicts);
//        return   R().data("dicts", dicts);
    }

    @GetMapping("/{id}")
    @Operation(description = "根据id查询字典", tags = "字典管理", method = "GET")
    public R getDictById(@PathVariable("id") Integer id) {
        //读取Redis获取数据
        Dict dict =(Dict) this.redisTemplate.opsForValue().get("dict");
        if(dict == null){//如果不存在：读取数据库，并存入到Redis中
            dict = this.dictService.getById(id);
            this.redisTemplate.opsForValue().set("dict",dict);
        }
        //如果存在：获取即可
        return R.ok().data("dict", dict);
    }

    @GetMapping("/")
    @Operation(description = "查询所有字典", tags = "字典管理", method = "GET")
    public R getDict() {
        //读取Redis获取数据
        List<Dict> dicts =(List<Dict>) this.redisTemplate.opsForValue().get("dicts");
        if(null == dicts  || dicts.size() == 0){
            dicts=this.dictService.selectAll();
            this.redisTemplate.opsForValue().set("dicts",dicts);
        }
        return  R.ok().data("list",dicts);
    }
    @DeleteMapping("/{id}")
    public R deleteDict(@PathVariable("id") Integer id) {
        //判断节点是否是父节点（且存在子节点）

        return R.setResult(ResponseEnum.SUCCESS);
    }

    @PostMapping("/import")
    @Operation(description = "导入数据", tags = "字典管理", method = "POST")
    public R importData(@RequestParam("file") MultipartFile file) {
        try {
            this.dictService.importData(file.getInputStream());
            return R.setResult(ResponseEnum.SUCCESS);
        } catch (IOException e) {
            throw new BusinessException(-301, "文件上传失败");
        }
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            // 这里注意设置响应头格式：
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            //attachment:是提供下载的方式
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelDTO.class).sheet("数据字典").doWrite(dictService.listDictData());
        } catch (IOException e) {
            //EXPORT_DATA_ERROR(104, "数据导出失败"),
            throw new BusinessException(104, "数据导出失败");
        }
    }
}
